package com.hmkj.core.service.userBank.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.account.AccountCashMapper;
import com.hmkj.core.mapper.userBank.UserBankMapper;
import com.hmkj.core.po.account.AccountCash;
import com.hmkj.core.po.userBank.UserBank;
import com.hmkj.core.service.userBank.UserBankService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 用户绑卡记录业务相关Service接口实现<br>
 *
 * @author lizhijie
 * @ClassName: UserBankServiceImpl
 * @date 2018-07-04 04:37:45
 */
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class UserBankServiceImpl implements UserBankService {

    @Resource
    private UserBankMapper userBankMapper;
    @Resource
    private AccountCashMapper cashMapper;

    @Override
    public GenericMapper<UserBank, Integer> _getMapper() {
        return userBankMapper;
    }

    @Override
    public void doVerify(UserBank userBank) throws Exception {
        UserBank bank = userBankMapper.selectByPrimaryKey(userBank.getId());
        if (bank == null) {
            throw new BussinessException("审核记录不存在");
        }
        bank.setRemark(userBank.getRemark());
        userBankMapper.updateByPrimaryKeySelective(bank);
    }

    @Override
    public void add(UserBank bank) {
        int i = userBankMapper.selectCount(new UserBank(b -> {
            b.setUserId(bank.getUserId());
            b.setBankNo(bank.getBankNo());
            b.setDelFlag(UserBank.DELFLAG.NORMAL.code);
        }));
        if (i > 0) throw new BussinessException("当前银行卡已存在");

        int i2 = userBankMapper.insert(bank);
        if (i2 != 1) throw new BussinessException("银行卡添加失败");
    }

    @Override
    public void del(Integer id, Integer userId) {
        if(null == id){
            throw new BussinessException("参数有误");
        }
        //校验当前银行卡是否有提现待审核
        UserBank userBank = userBankMapper.selectByPrimaryKey(id);
        if(null == userBank){
            throw new BussinessException("该银行卡已被删除或不存在");
        }
        if(userBank.getStatus() == UserBank.STATUS.T1.code){
            throw new BussinessException("认证中的银行卡不可删除");
        }
        int c = cashMapper.selectCount(new AccountCash(cash -> {
            cash.setBankNo(userBank.getBankNo());
            cash.setStatus(AccountCash.STATUS.T2.code);
            cash.setUserId(userId);
            cash.setDelFlag(AccountCash.DELFLAG.NORMAL.code);
        }));
        if (c > 0) {
            throw new BussinessException("当前银行卡有提现待审核,暂时无法删除");
        }
        int i2 = userBankMapper.updateByPrimaryKeySelective(new UserBank(u -> {
            u.setId(id);
            u.setDelFlag(UserBank.DELFLAG.DELETED.code);
        }));
        if (i2 != 1) {
            throw new BussinessException("删除失败");
        }
    }
}
